import { Injectable } from '@angular/core';
import {Subject,Observer,Observable,interval} from 'rxjs'

@Injectable({
  providedIn: 'root'
})
export class WsService {

  private subject: Subject<MessageEvent>;

  messageSubject;                                 // subject对象,用于发送事件
  private url;                                    // 默认请求的url
  private webSocket: WebSocket;

  constructor() {
    this.messageSubject = new Subject();


  }


  createWebSocket() {
    this.webSocket = new WebSocket(this.url);
    if(this.webSocket){
      this.webSocket.onopen=()=>{
        console.log('websocket 已连接');
      }

      this.webSocket.onmessage=(e)=>{
        // const message=JSON.parse(e.data);
        console.log('接收到消息时间', new Date().getTime(),e);
        this.messageSubject.next(e.data);
      }

      this.webSocket.onclose=(e)=>{
        console.log('连接关闭', e);
        this.webSocket.close();
      }

    }
  }

  connect(url) {
    if (!!url) {
      this.url = url;
    }
    // 创建websocket对象
    this.createWebSocket();
  }

  sendMessage(message) {
    this.webSocket.send(message);
  }
}
